<?php
/**
 * PHPECS社交电商系统，使用thinkphp框架+MySQL数据库编写的小程序商城系统，基于LGPL协议开源授权
 * @package phpecs
 * @author qq(123865789)
 * @copyright 2018-2020 深圳塔灯网络科技有限公司
 * @version 2.0
 * @license http://www.phpecs.com/lgpl.html phpecs开源授权协议：GNU Lesser General Public License
 **/
namespace app\hgapi\controller;
use app\hgapi\model\user\UserRole;
use app\hgapi\model\user\User;

class Login extends Auth{

    /**
     * 获取appid
     */
    public function get_appid(){
        $code = input('code'); //获取code码
        $name = input('name'); //微信昵称
        $portrait = input('portrait'); //用户头像
        $page = input('page'); //用户类型
        $upper = input('upper'); //上级推广账户 第一次注册的时候才能添加
        $secret = secret();
        $json = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $secret['appid'] .
            '&secret=' . $secret['secret_key'] . '&js_code=' . $code . '&grant_type=authorization_code';
        header("Content-Type: application/json");
        $contents = file_get_contents($json);
        $contents = json_decode($contents, true);
        $openid = $contents['openid'];
        $session_key = $contents['session_key'];
        if (!$openid) errorCode('登陆失败');
        $find = User::getUserInfo(['openid' => $openid], '');
        //没有此openid就返回生成的id 有的话就返回个人信息
        if (!$find){
            $arr = [
                'openid' => $openid,
                'name' => base64_encode($name),
                'real_name' => $name,
                'portrait' => $portrait,
                'upper' => (int) $upper ? $upper : 0,
                'time' => time()
            ];
            $id = User::add($arr);
            $arr2 = [
                'uid' => $id,
                'business' => $page == 8 ? 1 : 0,
            ];
            UserRole::add($arr2);
            $result = array(
                'session_key' => $session_key,
                'openid' => $openid,
                'id' => $id,
                'is_jin' => 0,
            );
            successCode($result);
        }else{
            $role = UserRole::getRole($find['id']);
            if ($role['business'] == 0 && $page == 8){ //当前账户是普通用户才能绑定账户类型 如果是绑定业务员才能直接修改
                UserRole::upField($find['id'], 'business', 1);
            }
            $arr['name'] = base64_encode($name);
            $arr['real_name'] = $name;
            $arr['portrait'] = $portrait;
            User::upUserInfo(['id' => $find['id']], $arr);
            $result = array(
                'session_key' => $session_key,
                'openid' => $find['openid'],
                'id' => $find['id'],
                'is_jin' => $find['is_jin'],
            );
            successCode($result);
        }
    }
}